package com.ninjas.module.common.page;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.List;

/**
 * 分页工具类
 */
public class PageUtils extends PageHelper {

    public static final String PAGE_NUM = "pageNum";
    public static final String PAGE_SIZE = "pageSize";

    private static Integer getParameter(String name, Integer defaultValue) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        if (attributes != null) {
            String pageNum = attributes.getRequest().getParameter(name);
            if (StringUtils.hasText(pageNum)) {
                return Integer.parseInt(pageNum);
            }
        }
        return defaultValue;
    }

    public static void startPage() {
        PageHelper.startPage(
                getParameter(PAGE_NUM, 1),
                getParameter(PAGE_SIZE, 10));
    }

    public static void clearPage() {
        PageHelper.clearPage();
    }

    public static long getTotal(List<?> list) {
        return new PageInfo<>(list).getTotal();
    }
}
